var table;
var moduleId;
var jsoneditor_default, jsoneditor_api, jsoneditor_database;
var jsoneditor_data;
$(function () {

    jsoneditor_default = new JSONEditor(document.getElementById("data_source_default"), {mode: 'form'}, {});
    jsoneditor_api = new JSONEditor(document.getElementById("data_source_api"), {mode: 'view'}, {"text": "等待api回传数据中..."});
    jsoneditor_database = new JSONEditor(document.getElementById("data_source_database"), {mode: 'view'}, {"text": "等待数据库回传数据中..."});

    initTable();

    $(".dataMenu-post").on('click', function () {
        var tag = $(this).attr("data-tag");
        postModuleData(tag);
    });

});

//每次操作之后的查询
function queryData() {
    table.ajax.reload();
}

function nullToString(obj) {
    if (typeof (obj) == "undefined" || obj == null || obj === "") {
        return "";
    } else {
        return obj;
    }
}

function getParam(data) {
    var param = {};
    param.panelName = $('#searchForName').val();
    param.draw = data.draw;
    param.size = data.length;
    param.current = (data.start / data.length) + 1;//当前页码
    return param;
}

//初始化表格
function initTable() {
    table = $('#table').DataTable({
        deferRender: true,
        serverSide: true,
        searching: false,
        ordering: false,
        sort: true,
        searchDelay: 200,
        autoWidth: true,
        processing: true,
        pageLength: 10,
        pagingType: "full_numbers", //分页样式：simple,simple_numbers,full,full_numbers
        ajax: function (data, callback, settings) {
            $.ajax({
                type: "post",
                url: ctp + "/module/queryList",
                cache: false,
                data: JSON.stringify(getParam(data)),
                dataType: "json",
                contentType: "application/json",
                success: function (result) {
                    if (result.code == "200") {
                        var returnData = {};
                        returnData.draw = result.draw;//这里直接自行返回了draw计数器,应该由后台返回
                        returnData.recordsTotal = result.data.total;//返回数据全部记录
                        returnData.recordsFiltered = result.data.total;//后台不实现过滤功能，每次查询均视作全部结果
                        returnData.data = result.data.records;//返回的数据列表
                        callback(returnData);
                    } else {
                        alert(result.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("网络异常");
                }
            });
        },
        columnDefs: [
            {
                "defaultContent": "",
                "targets": "_all"
            }
        ],
        columns: [
            {
                "data": 'panelName',
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return nullToString(data);
                }
            },
            {
                "data": "elementName",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return nullToString(data);
                }
            },
            {
                "data": "openUrl",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return "<a href='javascript:void(0);'  data-module-id='" + full.moduleId + "' class='btn btn-sm btn-link' onclick='editDataSource(this)'> 数据源</a>";
                },
                "width": "100px"
            }
        ],
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "每页 _MENU_ 项",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项。",
            "sInfoEmpty": "当前显示第 0 至 0 项，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页",
                "sJump": "跳转"
            },
            "oAria": {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        },
        dom: "<'#myTools.am-g'<'am-u-sm-3'<'am-btn-toolbar'<'#mybuttons.am-btn-group am-btn-group-xs'>>><'#mySearch.am-u-sm-6'><'am-u-sm-3'<'#query.am-input-group am-input-group-sm w100'>>>" +
            "t" +
            "<'am-g'<'am-u-sm-4'i><'am-u-sm-4'r><'am-u-sm-4'p>>",
        createdRow: function (row, data, dataIndex) {
            $(row).attr("data-module-id", data.moduleId);
        },
        initComplete: function () {
            $("#myTools").after("<br/>");
            //$("#mybuttons").append('<button type="button" class="am-btn am-btn-default am-btn-success" id = "newModule"><span class="am-icon-plus"></span> 新增</button>');
            //$("#mybuttons").append('<button type="button" class="am-btn am-btn-default am-btn-secondary" id = "updateModule"><span class="am-icon-save"></span> 修改</button>');
            //$("#mybuttons").append('<button type="button" class="am-btn am-btn-default am-btn-danger"><span class="am-icon-trash-o"></span> 删除</button>');
            $("#mySearch").append('<div class="am-form-group"></div>');
            $("#query").append('<input type="text" class="am-form-field" id = "searchForName" placeholder="请输入大屏名称"><span class="am-input-group-btn"><button class="am-btn  am-btn-default am-btn-success tpl-am-btn-success am-icon-search" id = "queryForName" type="button"></button></span>');

            //查询按钮
            $('#queryForName').on('click', function () {
                table.ajax.reload();
            })
        }
    });
}

//修改数据源设置
function updateModuleData() {
    var parm = {};
    parm.moduleId = moduleId;
    jsoneditor_data.default = jsoneditor_default.get();
    jsoneditor_data.api = $('#text_source_api').val();
    jsoneditor_data.database = $('#text_source_database').val();
    parm.dataSource = JSON.stringify(jsoneditor_data);
    save(parm);
}

function save(parm) {
    $.ajax({
        type: "post",
        url: ctp + "/module/insertModule",
        cache: false,
        data: JSON.stringify(parm),
        dataType: "json",
        contentType: "application/json",
        success: function (result) {
            if (result.code == "200") {
                queryData();
                alert("保存成功");
                $("#insertModule").modal('close');
                emptyData();
            } else {
                alert(result.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("网络异常");
        }
    });
}


//数据源处理
function editDataSource(obj) {
    moduleId = $(obj).attr("data-module-id");
    var rowNum = table.cell($(obj).closest("td")[0]).index().row;
    var json = JSON.parse(table.data()[rowNum].dataSource);
    jsoneditor_data = json;
    postModuleData(json);
    $("#insertModule").modal({
        relatedTarget: this,
        closeViaDimmer: false, // 点击外部空白处不关闭弹窗
        closeOnConfirm: false, // 返回信息提示也不关闭弹窗
        keyboard: false, //按下esc键不会被关闭
    });
}


function postModuleData(type) {
    var api = $("#text_source_api").val();
    var database = $("#text_source_database").val();
    if (type == "default") {
        jsoneditor_default.setText(JSON.stringify(jsoneditor_data.default));
    } else if (type == "api") {
        if (api) {
            $.ajax({
                type: "post",
                url: api,
                success: function (data) {
                    jsoneditor_api.setText(data);
                },
                error: function () {
                    jsoneditor_api.setText({"text": "请求api失败..."});
                }
            });
        }
    } else if (type == "database") {
        if (database) {
            $.ajax({
                type: "post",
                cache: false,
                data: {"database": database},
                url: ctp + "/module/getModuleDatabase",
                success: function (result) {
                    if (result.code == "200") {
                        var allData = JSON.stringify(result.data);
                        jsoneditor_database.setText(allData);
                    } else {
                        alert(result.msg);
                    }
                },
                error: function () {
                    jsoneditor_database.setText({"text": "请求数据库失败..."});
                }
            });
        }
    } else {
        jsoneditor_default.setText(JSON.stringify(jsoneditor_data.default));
        if (api) {
            $.ajax({
                type: "post",
                url: api,
                success: function (data) {
                    jsoneditor_api.setText(data);
                },
                error: function () {
                    jsoneditor_api.setText({"text": "请求api失败..."});
                }
            });
        }
        if (database) {
            $.ajax({
                type: "post",
                data: database,
                url: ctp + "/getModuleDatabase",
                success: function (data) {
                    jsoneditor_database.setText(data);
                },
                error: function () {
                    jsoneditor_database.setText({"text": "请求数据库失败..."});
                }
            });
        }
    }

}

function emptyData() {
    $('#text_source_api').val('');
    $('#text_source_database').val('');
    var api_json = {"text": "等待api回传数据中..."};
    var database_json = {"text": "等待数据库回传数据中..."};
    jsoneditor_api.setText(JSON.stringify(api_json));
    jsoneditor_database.setText(JSON.stringify(database_json));
}

